<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>添加商品</el-breadcrumb-item>

		</el-breadcrumb>
		<!-- 卡片区域 -->
		<el-card>
			<!-- 警告区域 -->
			<el-alert title="添加商品信息!" center="" type="info" show-icon :closable="false">
			</el-alert>
			<!-- 步骤条 -->
			<el-steps :space="200" :active="activeindex - 0" align-center finish-status="success">
				<el-step title="基本信息"></el-step>
				<el-step title="商品参数"></el-step>
				<el-step title="商品属性 "></el-step>
				<el-step title="商品图片"></el-step>
				<el-step title="商品内容"></el-step>
				<el-step title="完成"></el-step>
			</el-steps>
			<!-- 左侧tab栏 -->
			<el-form :model="addForm" :rules="addFormrules" ref="addruleFormRef" label-width="100px"
				label-position="top">

				<!-- 当我们切换tab栏时会将name值绑定到v-model中 v-model绑定步骤栏下标实现同步切换 -->
				<el-tabs @tab-click="tabClicked" v-model="activeindex" :tab-position="tabPosition"
					:before-leave="beforeTabLeave">
					<el-tab-pane label="基本信息" name="0">
						<el-form-item label="商品名称" prop="goods_name">
							<el-input v-model="addForm.goods_name"></el-input>
						</el-form-item>
						<el-form-item label="商品价格" prop="goods_price">
							<el-input type="number" v-model="addForm.goods_price"></el-input>
						</el-form-item>
						<el-form-item label="商品重量" prop="goods_weight">
							<el-input type="number" v-model="addForm.goods_weight"></el-input>
						</el-form-item>
						<el-form-item label="商品数量" prop="goods_number">
							<el-input type="number" v-model="addForm.goods_number"></el-input>
						</el-form-item>
						<el-form-item label="商品分类" prop="goods_cat">
							<el-cascader v-model="addForm.goods_cat" :options="catelist" :props="cateProps"
								@change="handleChange"></el-cascader>
						</el-form-item>

					</el-tab-pane>
					<el-tab-pane label="商品参数" name="1">
						<el-form-item :label="item.attr_name" v-for="item in manytabdata" :key="item.attr_id">
							<!-- 复选框组 -->
							<el-checkbox-group v-model="item.attr_vals">
								<el-checkbox border v-for="(cb,i) in item.attr_vals" :label="cb" :key="i"></el-checkbox>

							</el-checkbox-group>
						</el-form-item>

					</el-tab-pane>
					<el-tab-pane label="商品属性" name="2">
						<el-form-item :label="item.attr_name" v-for="item in onlytabdata" :key="item.attr_id">
							<el-input v-model="item.attr_vals"></el-input>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品图片" name="3">
						<!-- action上传路径地址 -->
						<el-upload :on-success="handleSuccess" :headers="hearderObj"
							action="http://127.0.0.1:8888/api/private/v1/upload" :on-preview="handlePreview"
							:on-remove="handleRemove" list-type="picture">
							<el-button size="small" type="primary">点击上传</el-button>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="商品内容" name="4">
						<!-- 富文本编辑器组件 -->
						<quill-editor v-model="addForm.goods_introduce"></quill-editor>
						<el-button @click="add" class="addbtn" type="primary">添加商品</el-button>
					</el-tab-pane>

				</el-tabs>
			</el-form>
		</el-card>
		<!-- 图片预览对话框 -->
		<el-dialog style="width: 100%;" title="图片预览" :visible.sync="previewVisible" width="50%">
			<img class="previewImg" :src="previewPath" />

		</el-dialog>


	</div>
</template>

<script>
	import _ from 'lodash'
	export default {
		data() {
			return {
				activeindex: '0',
				tabPosition: 'left',
				// 添加商品的表单数据对象
				addForm: {
					goods_name: '',
					goods_price: 0,
					goods_weight: 0,
					goods_number: 0,
					goods_cat: [],
					// 图片临时路径数组
					pics: [],
					// 商品描述
					goods_introduce: '',
					attrs: []

				},
				previewPath: '',
				// 预览对话框显示与隐藏
				previewVisible: false,
				// 表单验证对象
				addFormrules: {
					goods_name: [{
							required: true,
							message: '请输入商品名称',
							trigger: 'blur'
						},

					],
					goods_price: [{
						required: true,
						message: '请输入商品价格',
						trigger: 'blur'
					}],
					goods_weight: [{
						required: true,
						message: '请输入商品重量',
						trigger: 'blur'
					}],
					goods_number: [{
						required: true,
						message: '请输入商品数量',
						trigger: 'blur'
					}],
					goods_cat: [{
						required: true,
						message: '选择商品分类',
						trigger: 'blur'
					}]

				},
				catelist: [],
				cateProps: {
					label: 'cat_name',
					value: 'cat_id',
					children: 'children'

				},
				//动态参数列表数据
				manytabdata: [],
				// 静态参数列表数据
				onlytabdata: [],
				// 上传图片需要携带的token请求头
				hearderObj: {
					Authorization: window.sessionStorage.getItem('token')
				}

			}
		},

		created() {
			this.getCateList()

		},
		computed: {
			cateId() {
				if (this.addForm.goods_cat.length === 3) {
					return this.addForm.goods_cat[2]
				}
			}
		},
		methods: {
			// 获取分类数据
			async getCateList() {
				const {
					data: res
				} = await this.$http.get('categories')
				if (res.meta.status != 200) {
					return this.$message.error("获取商品分类失败")
				}
				//把数据列表赋值给catelist
				this.catelist = res.data
				console.log(this.catelist)

			},
			// 级联选择器选中项发生变化
			handleChange() {
				if (this.addForm.goods_cat.length !== 3) {
					this.addForm.goods_cat = []
				}
				console.log(this.addForm.goods_cat)
			},
			// oldactiveName=即将离开的标签页  activeName跳转到的标签页
			beforeTabLeave(activeName, oldactiveName) {
				if (oldactiveName === '0' && this.addForm.goods_cat.length !== 3) {
					this.$message.error("请先选择商品分类")
					return false
				}
			},
			// 点击tab
			async tabClicked() {
				// 证明访问的是动态参数面板
				if (this.activeindex === '1') {
					const {
						data: res
					} = await this.$http.get(`categories/${this.cateId}/attributes`, {
						params: {
							sel: 'many'
						}
					})

					if (res.meta.status != 200) {
						return this.$message.error("获取参数失败")
					}

					this.manytabdata = res.data
					res.data.forEach(item => {
						item.attr_vals =
							item.attr_vals.length === 0 ? [] :
							item.attr_vals.split(",")

					})
					console.log(res.data)

				} else if (this.activeindex === '2') {
					const {
						data: res
					} = await this.$http.get(`categories/${this.cateId}/attributes`, {
						params: {
							sel: 'only'
						}
					})

					if (res.meta.status != 200) {
						return this.$message.error("获取参数失败")
					}
					console.log(res.data)
					this.onlytabdata = res.data
					res.data.forEach(item => {
						item.attr_vals =
							item.attr_vals.length === 0 ? [] :
							item.attr_vals.split(",")

					})


				}


			},
			// 预览图片处理
			handlePreview(file) {
				this.previewPath = file.response.data.url
				this.previewVisible = true
			},
			// 处理移除图片
			handleRemove(file) {

				// 获取将要删除的图片的临时路径
				const filePath = file.response.data.tmp_path
				// 从pics数组中找到这个图片对应的索引值
				const i = this.addForm.pics.findIndex(x =>
					x.pic === filePath)
				// 调用数组的splice方法把该图片路径从数组中删除
				this.addForm.pics.splice(i, 1)
				console.log(this.addForm)
			},
			// 图片上传成功处理
			handleSuccess(reponse) {
				//拼接得到一个图片信息对象
				const picinfo = {
					pic: reponse.data.tmp_path
				}
				this.addForm.pics.push(picinfo)
				console.log(this.addForm)
			},
			// 添加商品提交按钮
			add() {
				this.$refs.addruleFormRef.validate(async valid => {
					if (!valid) return this.$message.error("请填写必要的表单项")
					//可以发起用户请求
					// 深拷贝
					const form = _.cloneDeep(this.addForm)
					form.goods_cat = form.goods_cat.join(',')

					// 处理动态参数
					this.manytabdata.forEach(item => {
						const newInfo = {
							attr_id: item.attr_id,
							attr_value: item.attr_vals.join(' ')

						}
						this.addForm.attrs.push(newInfo)
					})

					// 处理静态属性
					this.onlytabdata.forEach(item => {
						const newInfo = {
							attr_id: item.attr_id,
							attr_value: item.attr_vals

						}
						this.addForm.attrs.push(newInfo)
					})
					form.attrs = this.addForm.attrs
					console.log(form)
					const {
						data: res
					} = await this.$http.post('goods', form)
					if (res.meta.status != 201) {
						return this.$message.error(res.meta.msg)
					}
					this.$message.success(res.meta.msg)
					this.$router.push('/goods')

				})
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	.el-checkbox {
		margin: 0 5px 0 0 !important;
	}

	.previewImg {
		width: 100%;
	}

	.addbtn {
		margin-top: 10px;
	}
</style>
